package inutan.common.utils;

import org.ricks.common.lang.Logger;
import org.ricks.net.http.HttpStatus;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/**
 * broker http client 工具
 * 核心目的：请求登录服校验token 获取userId
 * 业务服 load 玩家数据
 */
public class HttpUtils {

    /**
     * 5秒超时
     */
    private static Duration ofSeconds = Duration.ofSeconds(5);

    private static HttpClient httpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            //.executor(InutanActors.httpClient)
            .connectTimeout(ofSeconds)
            .build();

    private static String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36";

    public static String doGet(String url) {
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(ofSeconds)
                .GET()
                .build();
        try {
            HttpResponse<String> response = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            return response.statusCode() == HttpStatus.OK.value() ? response.body() : "";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void doAsyncPost(String url,String data) {
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json")
                .timeout(ofSeconds)
                .POST(data.isBlank() ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(data))
                .build();
        try {
            httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
